package com.ly.web.controller.system;

import java.util.List;
import java.util.stream.Collectors;

import com.ly.common.annotation.Log;
import com.ly.common.constant.UserConstants;
import com.ly.common.core.controller.BaseController;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.core.domain.entity.*;
import com.ly.common.core.domain.model.LoginUser;
import com.ly.common.core.page.TableDataInfo;
import com.ly.common.enums.BusinessType;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.ServletUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.poi.ExcelUtil;
import com.ly.framework.web.service.TokenService;
import com.ly.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * User
 * @author
 */
@Api (value = "Dept", tags = "用户信息")
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping ("/system/user")
public class SysUserController extends BaseController {

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysPostService postService;

    @Resource
    private TokenService tokenService;
    @Resource
    private IUserEducationalService iUserEducationalService;
    @Resource
    private IUserMajorSocialRelationService iUserMajorSocialRelationService;
    @Resource
    private IUserWorkExperienceService iUserWorkExperienceService;

    /**
     * 获取用户列表
     */
    @PreAuthorize ("@ss.hasPermi('system:user:list')")
    @GetMapping ("/list")
    @ApiOperation ("获取用户列表")
    public TableDataInfo list (SysUser user) {
        //startPage ();
        List<SysUser> list = userService.selectUserList ( user );
        TableDataInfo tableDataInfo = new TableDataInfo ();
        tableDataInfo.setRows ( list );
        tableDataInfo.setTotal ( userService.queryCount ( user ) );
        return tableDataInfo;
    }

    @Log (title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize ("@ss.hasPermi('system:user:export')")
    @GetMapping ("/export")
    @ApiOperation ("导出用户列表")
    public AjaxResult export (SysUser user) {
        List<SysUser> list = userService.selectUserList ( user );
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser> ( SysUser.class );
        return util.exportExcel ( list, "用户数据" );
    }

    @Log (title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize ("@ss.hasPermi('system:user:import')")
    @PostMapping ("/importData")
    @ApiOperation ("导入用户列表")
    public AjaxResult importData (MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser> ( SysUser.class );
        List<SysUser> userList = util.importExcel ( file.getInputStream () );
        LoginUser loginUser = tokenService.getLoginUser ( ServletUtils.getRequest () );
        String operName = loginUser.getUsername ();
        String message = userService.importUser ( userList, updateSupport, operName );
        return AjaxResult.success ( message );
    }

    @GetMapping ("/importTemplate")
    public AjaxResult importTemplate () {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser> ( SysUser.class );
        return util.importTemplateExcel ( "用户数据" );
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize ("@ss.hasPermi('system:user:query')")
    @GetMapping (value = {"/", "/{userId}"})
    @ApiOperation ("根据用户编号获取详细信息")
    public AjaxResult getInfo (@PathVariable (value = "userId", required = false) String userId) {
        AjaxResult ajax = AjaxResult.success ();
        List<SysRole> roles = roleService.selectRoleAll ();
        ajax.put ( "roles", SysUser.isAdmin ( userId ) ? roles : roles.stream ().filter ( r -> ! r.isAdmin () ).collect ( Collectors.toList () ) );
        ajax.put ( "posts", postService.selectPostAll () );
        if ( StringUtils.isNotNull ( userId ) ) {
            SysUser sysUser = userService.selectUserById ( userId );
            //绑定社会关系
            UserMajorSocialRelationEntity major = new UserMajorSocialRelationEntity ();
            major.setUserId ( userId );
            List<UserMajorSocialRelationEntity> userMajorSocialRelationEntities = iUserMajorSocialRelationService.selectUserMajorSocialRelationEntityList ( major );
            sysUser.setUserMajorSocialRelationEntities ( userMajorSocialRelationEntities );
            //绑定教育经历
            UserEducationalEntity educational = new UserEducationalEntity ();
            educational.setUserId ( userId );
            List<UserEducationalEntity> userEducationalEntities = iUserEducationalService.selectUserEducationalEntityList ( educational );
            sysUser.setUserEducationalEntities ( userEducationalEntities );
            //绑定工作经历
            UserWorkExperienceEntity work = new UserWorkExperienceEntity ();
            work.setUserId ( userId );
            List<UserWorkExperienceEntity> userWorkExperienceEntities = iUserWorkExperienceService.selectUserWorkExperienceEntityList ( work );
            sysUser.setUserWorkExperienceEntities ( userWorkExperienceEntities );
            ajax.put ( AjaxResult.DATA_TAG, sysUser );
            ajax.put ( "postIds", postService.selectPostListByUserId ( userId ) );
            ajax.put ( "roleIds", roleService.selectRoleListByUserId ( userId ) );
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize ("@ss.hasPermi('system:user:add')")
    @Log (title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation ("新增用户")
    public AjaxResult add (@Validated @RequestBody SysUser user) {
        if ( UserConstants.NOT_UNIQUE.equals ( userService.checkUserNameUnique ( user.getUserName () ) ) ) {
            return AjaxResult.error ( "新增用户'" + user.getUserName () + "'失败，登录账号已存在" );
        } else if ( UserConstants.NOT_UNIQUE.equals ( userService.checkPhoneUnique ( user ) ) ) {
            return AjaxResult.error ( "新增用户'" + user.getUserName () + "'失败，手机号码已存在" );
        } else if ( UserConstants.NOT_UNIQUE.equals ( userService.checkEmailUnique ( user ) ) ) {
            return AjaxResult.error ( "新增用户'" + user.getUserName () + "'失败，邮箱账号已存在" );
        }
        user.setCreateBy ( SecurityUtils.getUsername () );
        user.setPassword ( SecurityUtils.encryptPassword ( user.getPassword () ) );
        return toAjax ( userService.insertUser ( user ) );
    }

    /**
     * 修改用户
     */
    @PreAuthorize ("@ss.hasPermi('system:user:edit')")
    @Log (title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation ("修改用户")
    public AjaxResult edit (@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed ( user );
        if ( UserConstants.NOT_UNIQUE.equals ( userService.checkPhoneUnique ( user ) ) ) {
            return AjaxResult.error ( "修改用户'" + user.getUserName () + "'失败，手机号码已存在" );
        } else if ( UserConstants.NOT_UNIQUE.equals ( userService.checkEmailUnique ( user ) ) ) {
            return AjaxResult.error ( "修改用户'" + user.getUserName () + "'失败，邮箱账号已存在" );
        }
        user.setUpdateBy ( SecurityUtils.getUsername () );
        return toAjax ( userService.updateUser ( user ) );
    }

    /**
     * 删除用户
     */
    @PreAuthorize ("@ss.hasPermi('system:user:remove')")
    @Log (title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping ("/{userIds}")
    @ApiOperation ("删除用户")
    public AjaxResult remove (@PathVariable String[] userIds) {
        return toAjax ( userService.deleteUserByIds ( userIds ) );
    }

    /**
     * 重置密码
     */
    @PreAuthorize ("@ss.hasPermi('system:user:resetPwd')")
    @Log (title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping ("/resetPwd")
    @ApiOperation ("重置密码")
    public AjaxResult resetPwd (@RequestBody SysUser user) {
        userService.checkUserAllowed ( user );
        user.setPassword ( SecurityUtils.encryptPassword ( user.getPassword () ) );
        user.setUpdateBy ( SecurityUtils.getUsername () );
        return toAjax ( userService.resetPwd ( user ) );
    }

    /**
     * 状态修改
     */
    @PreAuthorize ("@ss.hasPermi('system:user:edit')")
    @Log (title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping ("/changeStatus")
    @ApiOperation ("状态修改")
    public AjaxResult changeStatus (@RequestBody SysUser user) {
        userService.checkUserAllowed ( user );
        user.setUpdateBy ( SecurityUtils.getUsername () );
        return toAjax ( userService.updateUserStatus ( user ) );
    }
}
